import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  BeforeInsert,
  OneToMany,
  OneToOne,
  JoinColumn,
} from 'typeorm';
import * as bcrypt from 'bcryptjs';
import { UserLogin } from './user-login.entity';
import { UserBase } from './user-base.entity';
export enum Sex {
  '女' = 0,
  '男' = 1,
  '' = 2,
}
@Entity('user') // 指定表名称为 'im_user'
export class User {
  @PrimaryGeneratedColumn({ comment: '自增主键 主键id' })
  user_id: string;

  @Column({ type: 'varchar', name: 'name', comment: '姓名', length: 50 })
  name: string;

  @Column({
    type: 'varchar',
    name: 'password',
    comment: '密码',
    length: 200,
    select: false, //表示隐藏此列 查询过程中不显示此列
  })
  password: string;

  @Column({ comment: '手机号', length: 20 })
  phone: string;

  @OneToMany(() => UserLogin, (login) => login.user)
  @JoinColumn({ name: 'user_id', referencedColumnName: 'user_id' })
  logins: UserLogin[];

  @OneToOne(() => UserBase) // 定义与 UserBase 的一对一关系
  // @JoinColumn() // 指定外键列默认id
  @JoinColumn({ name: 'user_id', referencedColumnName: 'user_id' }) // 指定外键列
  user_base: UserBase; // 关系属性名称必须与查询中使用的名称一样

  @Column({
    comment: '创建时间',
    name: 'create_time',
    type: 'timestamp',
    default: () => 'CURRENT_TIMESTAMP',
  })
  createTime: Date;

  @Column({
    comment: '更新时间',
    name: 'update_time',
    type: 'timestamp',
    default: () => 'CURRENT_TIMESTAMP',
  })
  updateTime: Date;

  // 执行之前处理函数
  @BeforeInsert()
  async encryptPassword() {
    if (this.password) {
      this.password = await bcrypt.hashSync(this.password, 10); //加密功能
    }
  }
}
